package com.ckd.flyingtrip.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.javabean.JsonBean;
import com.ckd.flyingtrip.javabean.UserInfoAddressBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.GetJsonDataUtil;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;
import com.suke.widget.SwitchButton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UserInfoAddressAddActivity extends BaseActivity {

    @BindView(R.id.activity_userinfo_address_add_name)
    EditText name;
    @BindView(R.id.activity_userinfo_address_add_phone)
    EditText phone;
    @BindView(R.id.activity_userinfo_address_add_addressText)
    TextView addressText;
    @BindView(R.id.activity_userinfo_address_add_addressTextView)
    EditText addressTextView;
    @BindView(R.id.activity_userinfo_address_add_switchButton)
    SwitchButton switchButton;
    @BindView(R.id.activity_userinfo_address_add_labelText1)
    TextView labelText1;
    @BindView(R.id.activity_userinfo_address_add_labelText2)
    TextView labelText2;
    @BindView(R.id.activity_userinfo_address_add_labelText3)
    TextView labelText3;
    @BindView(R.id.toolber_color_title)
    TextView toolberTitle;
    @BindView(R.id.toolber_color_right)
    TextView activityUserinfoAddressAddSave;

    private String labelText = "2";
    private String addressDefault = "0";

    private Thread thread;
    private final int MSG_LOAD_DATA = 0x0001;
    private final int MSG_LOAD_SUCCESS = 0x0002;
    private final int MSG_LOAD_FAILED = 0x0003;
    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private String addressId = "";


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");

        ArrayList<JsonBean> jsonBean = parseData(JsonData);
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {
            ArrayList<String> cityList = new ArrayList<>();
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);
                ArrayList<String> city_AreaList = new ArrayList<>();

                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);
            }
            options2Items.add(cityList);

            options3Items.add(province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public ArrayList<JsonBean> parseData(String result) {
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo_address_add);
        ButterKnife.bind(this);

        initView();
        initListener();

    }

    private void initListener() {
        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    addressDefault = "1";
                } else {
                    addressDefault = "0";
                }
            }
        });
    }

    private void initView() {
        activityUserinfoAddressAddSave.setVisibility(View.VISIBLE);
        toolberTitle.setText(getIntent().getStringExtra("title"));

        if (getIntent().getStringExtra("title").equals("修改地址")) {
            UserInfoAddressBean.DataBean bean = (UserInfoAddressBean.DataBean) getIntent().getSerializableExtra("data");
            addressId = bean.getAddressId();
            name.setText(bean.getName());
            phone.setText(bean.getPhone());
            switch (bean.getAddressType()) {
                case "0":
                    labelText = "0";
                    labelText1.setTextColor(ContextCompat.getColor(this, R.color.dengluse));
                    labelText1.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_fd5boe_border));
                    labelText2.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                    labelText2.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                    labelText3.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                    labelText3.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                    break;
                case "1":
                    labelText = "1";
                    labelText1.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                    labelText1.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                    labelText2.setTextColor(ContextCompat.getColor(this, R.color.dengluse));
                    labelText2.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_fd5boe_border));
                    labelText3.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                    labelText3.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                    break;
                case "2":
                    labelText = "2";
                    labelText1.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                    labelText1.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                    labelText2.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                    labelText2.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                    labelText3.setTextColor(ContextCompat.getColor(this, R.color.dengluse));
                    labelText3.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_fd5boe_border));
                    break;
            }

            addressText.setText(bean.getRegion());
            addressTextView.setText(bean.getAddress());
            switch (bean.getAddressDefault()) {
                case "1":
                    switchButton.setChecked(true);
                    break;
                case "0":
                    switchButton.setChecked(false);
                    break;
            }

        }

        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @OnClick({R.id.toolber_color_back, R.id.toolber_color_right, R.id.activity_userinfo_address_add_address,
            R.id.activity_userinfo_address_add_labelText1, R.id.activity_userinfo_address_add_labelText2, R.id.activity_userinfo_address_add_labelText3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolber_color_back:
                finish();
                break;
            case R.id.toolber_color_right:
                if (name.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请填写收货人名称！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!Tools.isPhoneNumber(phone.getText().toString().trim())) {
                    Toast.makeText(this, "请填写正确的手机号！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (addressText.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请选择所在地区！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (addressTextView.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请填写详细地址！", Toast.LENGTH_SHORT).show();
                    return;
                }

                switch (getIntent().getStringExtra("title")) {
                    case "添加地址":
                        initSave();
                        break;
                    case "修改地址":
                        initModifySave();
                        break;
                }
                break;
            case R.id.activity_userinfo_address_add_address:
                initAddress();
                break;
            case R.id.activity_userinfo_address_add_labelText1:
                labelText = "0";
                labelText1.setTextColor(ContextCompat.getColor(this, R.color.dengluse));
                labelText1.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_fd5boe_border));
                labelText2.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                labelText2.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                labelText3.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                labelText3.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                break;
            case R.id.activity_userinfo_address_add_labelText2:
                labelText = "1";
                labelText1.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                labelText1.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                labelText2.setTextColor(ContextCompat.getColor(this, R.color.dengluse));
                labelText2.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_fd5boe_border));
                labelText3.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                labelText3.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                break;
            case R.id.activity_userinfo_address_add_labelText3:
                labelText = "2";
                labelText1.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                labelText1.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                labelText2.setTextColor(ContextCompat.getColor(this, R.color.dl_txt));
                labelText2.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_919594_border));
                labelText3.setTextColor(ContextCompat.getColor(this, R.color.dengluse));
                labelText3.setBackground(ContextCompat.getDrawable(this, R.drawable.shape_10_fd5boe_border));
                break;
        }
    }

    private void initModifySave() {
        String url = Constants.modifyaddress;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.e("添加地址", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    if (code.equals("1")) {
                        Toast.makeText(UserInfoAddressAddActivity.this, "修改成功！", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Log.i("站好", "账号");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismisProgressDialog();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("sss", volleyError + "");
                dismisProgressDialog();
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("addressId", addressId);
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("addressType", labelText);
                    json_url.put("address", addressTextView.getText().toString().trim());
                    json_url.put("name", name.getText().toString().trim());
                    json_url.put("phone", phone.getText().toString().trim());
                    json_url.put("addressDefault", addressDefault);
                    json_url.put("region", addressText.getText().toString().trim());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initSave() {
        String url = Constants.addaddress;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.e("添加地址", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    if (code.equals("1")) {
                        Toast.makeText(UserInfoAddressAddActivity.this, "添加成功！", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Log.i("站好", "账号");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismisProgressDialog();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("sss", volleyError + "");
                dismisProgressDialog();
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("addressType", labelText);
                    json_url.put("address", addressTextView.getText().toString().trim());
                    json_url.put("name", name.getText().toString().trim());
                    json_url.put("phone", phone.getText().toString().trim());
                    json_url.put("addressDefault", addressDefault);
                    json_url.put("region", addressText.getText().toString().trim());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initAddress() {

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                addressText.setText(tx);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .setContentTextSize(20)
                .build();

        pvOptions.setPicker(options1Items, options2Items, options3Items);
        pvOptions.show();
    }
}
